package com.chushouya.order.service.common.impl;

import com.alipay.api.response.AlipayOpenMiniOrderDeliveryModifyResponse;
import com.chushouya.manager.config.BizConfigEnum;
import com.chushouya.order.constants.*;
import com.chushouya.order.service.admin.AlipayOrderPayService;
import com.chushouya.order.service.api.AlipayOpenMiniOrderDeliveryModifyService;
import com.chushouya.order.service.common.CommonOrderActionService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import com.chushouya.manager.dto.admin.payment.UserPaymentMethodApiDTO;
import com.chushouya.manager.service.common.UserPaymentMethodApiService;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.admin.paymentlog.PaymentInfoDTO;
import com.chushouya.order.dto.admin.paymentlog.PaymentResultDTO;
import com.chushouya.order.service.common.OrderPaymentService;
import com.chushouya.order.service.common.OrderLogService;
import com.chushouya.manager.service.admin.ConfigService;
import com.google.common.base.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 订单支付公共服务实现类
 * 
 * @author chushouya
 * @date 2025-09-07
 */
@Slf4j
@Service
public class OrderPaymentServiceImpl implements OrderPaymentService {

    @Resource
    private UserPaymentMethodApiService userPaymentMethodApiService;
    
    @Resource
    private AlipayOrderPayService alipayOrderPayService;
    
    @Resource
    private OrderRepository orderRepository;
    
    @Resource
    private OrderLogService orderLogService;

    @Resource
    private CommonOrderActionService commonOrderActionService;

    @Resource
    private ConfigService configService;

    @Resource
    private AlipayOpenMiniOrderDeliveryModifyService alipayOpenMiniOrderDeliveryModifyService;

    /**
     * 支付宝私域ID
     */
    private static final Long ALIPAY_PRIVATE_PARTNER_ID = 100004L;

    @Override
    public PaymentResultDTO executeOrderPayment(OrderEntity orderEntity) {
        final Long partnerId = orderEntity.getPartnerId();
        PaymentResultDTO paymentResult = null;
        if (Objects.equal(partnerId, ALIPAY_PRIVATE_PARTNER_ID)) {
            //支付宝私域完成订单
            handleAlipayOrderPayment(orderEntity);
            return paymentResult;
        }

        // 校验订单状态
        shouldIgnorePaymentPartner(orderEntity);
        
        // 获取用户收款信息
        UserPaymentMethodApiDTO userPaymentMethod = userPaymentMethodApiService.selectByUserId(orderEntity.getUserId());
        if (userPaymentMethod == null) {
            throw Ex.business("用户收款信息不存在，请先设置收款信息");
        }

        // 调用支付接口
        PaymentInfoDTO paymentInfo = new PaymentInfoDTO();
        paymentInfo.setOrderId(orderEntity.getOrderId());
        paymentInfo.setAccountName(userPaymentMethod.getAccountName());
        paymentInfo.setAccountNumber(userPaymentMethod.getAccountNumber());

        try{
            paymentResult = alipayOrderPayService.alipayOrderPay(paymentInfo);
        }catch (Exception e){
            log.error("调用支付接口异常：{}", e.getMessage());
            orderLogService.addOrderActionLog(orderEntity.getOrderId(),
                    OrderActionEnum.PAY_ORDER.value(), Strings.format("调用支付接口异常：{}", e.getMessage()));

            throw Ex.business("调用支付接口异常：{}", e.getMessage());
        }

        // 更新订单支付状态
        if (PaymentStatusEnum.SUCCESS.value().equals(paymentResult.getStatus())) {
            // 支付成功，更新订单支付状态为已支付
            OrderEntity orderUpdate = new OrderEntity();
            orderUpdate.setOrderId(orderEntity.getOrderId());
            orderUpdate.setPayStatus(OrderPayStatusEnum.BALANCE.value());
            orderUpdate.setPayType(OrderPayTypeEnum.ALIPAY.value());
            orderRepository.updateByPrimaryKeySelective(orderUpdate);
            
            // 添加订单操作日志
            String remark = Strings.format("订单支付成功，支付金额：{}元，收款账号：{} {}",
                    orderEntity.getCompletePrice(), userPaymentMethod.getAccountName(), userPaymentMethod.getAccountNumber());
            orderLogService.addOrderActionLog(orderEntity.getOrderId(), 
                    OrderActionEnum.PAY_ORDER.value(), remark);
            
            // 完成订单
            final String msg = Strings.format("完成订单，订单金额:{}元,支付方式:{}", orderEntity.getCompletePrice(), OrderPayTypeEnum.getDesc(OrderPayTypeEnum.ALIPAY.value()));
            commonOrderActionService.completeOrder(orderEntity, OrderPayTypeEnum.ALIPAY.value(), orderEntity.getCompletePrice(), msg, OrderStatusEnum.COMPLETE.value());

            log.info("订单支付成功，订单ID：{}，支付日志ID：{}", orderEntity.getOrderId(), paymentResult.getPaymentLogId());
            
        } else {
            // 支付失败，记录失败日志但不更新订单状态
            String remark = Strings.format("订单支付失败：{}，支付金额：{}元，收款账号：{} {}",
                    paymentResult.getMessage(), orderEntity.getCompletePrice(), userPaymentMethod.getAccountName(), userPaymentMethod.getAccountNumber());
            orderLogService.addOrderActionLog(orderEntity.getOrderId(), 
                    OrderActionEnum.PAY_ORDER.value(), remark);
            
            log.error("订单支付失败，订单ID：{}，失败原因：{}", orderEntity.getOrderId(), paymentResult.getMessage());
            throw Ex.business("支付失败：{}", paymentResult.getMessage());
        }
        
        return paymentResult;
    }

    /**
     * 判断是否应该忽略支付的合作商
     * 
     * @return true-忽略支付，false-正常支付
     */
    private void shouldIgnorePaymentPartner(OrderEntity orderEntity) {
        final Long partnerId = orderEntity.getPartnerId();
        final String partnerName = orderEntity.getPartnerName();
        
        try {
            // 从配置中获取忽略支付的合作商ID列表
            String ignorePartnerConfig = configService.getStringConfig(BizConfigEnum.IGNORE_PAYMENT_PARTNER.getConfigKey());
            List<Long> ignorePartnerConfigList = Jsons.parseArray(ignorePartnerConfig, Long.class);

            if (ignorePartnerConfigList.contains(partnerId)) {
                log.debug("合作商ID: {} {} 在忽略支付列表中: {}", partnerId,partnerName, ignorePartnerConfig);
                final String msg = Strings.format("合作商 {} (ID: {}) 配置为忽略支付，跳过支付流程", partnerName, partnerId);
                orderLogService.addOrderActionLog(orderEntity.getOrderId(),
                        OrderActionEnum.PAY_ORDER.value(), msg);
                commonOrderActionService.completeOrder(orderEntity, OrderPayTypeEnum.OTHER.value(), orderEntity.getCompletePrice(),
                        msg, OrderStatusEnum.COMPLETE.value());
                throw Ex.business("合作商 {} (ID: {}) 配置为忽略支付，跳过支付流程", partnerName, partnerId);
            }
            
        } catch (Exception e) {
            log.error("检查忽略支付合作商配置时发生异常，合作商ID: {}, 错误: {}", partnerId, e.getMessage(), e);
            // 异常情况下不忽略支付，确保业务正常进行
        }
    }

    /**
     * 处理支付宝私域完成订单支付
     */
    private void handleAlipayOrderPayment(OrderEntity orderEntity) {
        final Long partnerId = orderEntity.getPartnerId();
        final Long orderId = orderEntity.getOrderId();
        if (!Objects.equal(partnerId, ALIPAY_PRIVATE_PARTNER_ID)) {
            return;
        }
        log.info("处理支付宝私域完成订单支付，订单ID：{}，合作商ID：{}", orderEntity.getOrderId(), partnerId);
        AlipayOpenMiniOrderDeliveryModifyResponse response = alipayOpenMiniOrderDeliveryModifyService.confirmOrder(orderId);
        if (response == null || !response.isSuccess()) {
            String errorMsg = response != null ? response.getSubMsg() : "无响应";
            log.error("支付宝私域完成订单支付失败，订单ID：{}，错误信息：{}", orderId, errorMsg);
            orderLogService.addOrderActionLog(orderId,
                    OrderActionEnum.PAY_ORDER.value(), Strings.format("支付宝私域完成订单支付失败，错误信息：{}", errorMsg));
            throw Ex.business("支付宝私域完成订单支付失败，错误信息：{}", errorMsg);
        }else{
            final String msg = Strings.format("支付宝阵地订单支付成功 ，支付金额：{}元", orderEntity.getCompletePrice());
            orderLogService.addOrderActionLog(orderEntity.getOrderId(),
                    OrderActionEnum.PAY_ORDER.value(), msg);
            commonOrderActionService.completeOrder(orderEntity, OrderPayTypeEnum.OTHER.value(), orderEntity.getCompletePrice(),
                    msg, OrderStatusEnum.COMPLETE.value());
        }
    }
}
